package com.hornsun.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by cwc on 2018/01/03 0024.
 */
public class TripleDesUtil {
    private static final String ALGORITHM = "DESede"; //定义加密算法,可用 DES,DESede,Blowfish
    public static void main(String[] args){
        System.out.println(encrypt("admin","(@^@)Hornsun!2017"));
        System.out.println(encrypt("123","(@^@)Hornsun!2017"));
        System.out.println(encrypt("12345678910","(@^@)Hornsun!2017"));
        System.out.println(encrypt("12345678@qq.com","(@^@)Hornsun!2017"));
    }
    private static byte[] encryptMode(String des, String password) throws Exception {
        SecretKey deskey = new SecretKeySpec(hex(password), ALGORITHM);
        Cipher c1 = Cipher.getInstance(ALGORITHM);
        c1.init(Cipher.ENCRYPT_MODE, deskey);
        return c1.doFinal(des.getBytes("UTF-8"));

    }

    private static byte[] decryptMode(String secret, String password) throws Exception {
        byte[] src = Base64.decodeBase64(secret);
        SecretKey deskey = new SecretKeySpec(hex(password), ALGORITHM);
        Cipher c1 = Cipher.getInstance(ALGORITHM);
        c1.init(Cipher.DECRYPT_MODE, deskey);
        return c1.doFinal(src);
    }

    private static byte[] hex(String ppassword) {
        byte[] bkeys = DigestUtils.md5Hex(ppassword).getBytes();
        byte[] enk = new byte[24];
        System.arraycopy(bkeys, 0, enk, 0, 24);
        return enk;
    }

    public static String encrypt(String normalContent, String password) {
        try {
            byte[] encryBytes = encryptMode(normalContent, password);
            return Base64.encodeBase64String(encryBytes);
        } catch (Exception e) {
            return normalContent;
        }
    }

    public static String decrypt(String encryptContent, String password) {
        try {
            byte[] decryptByte = decryptMode(encryptContent, password);
            return new String(decryptByte, "UTF-8");
        } catch (Exception e) {
            return encryptContent;
        }
    }
}
